//
//  BMSOpMergeCacheManager.m
//  WDBMS
//
//  Created by YeJary on 2025/5/14.
//

#import "BMSOpMergeCacheManager.h"

@interface BMSOpMergeCacheManager ()
@property (nonatomic, strong) NSString *cacheFilePath;
@property (nonatomic, strong) dispatch_queue_t ioQueue;
@end

@implementation BMSOpMergeCacheManager

+ (instancetype)shared {
    static BMSOpMergeCacheManager *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    return instance;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        _ioQueue = dispatch_queue_create("com.bms.cache.queue", DISPATCH_QUEUE_SERIAL);
        _cacheFilePath = [self defaultCachePath];
    }
    return self;
}

- (NSArray<NSDictionary *> *)loadCachedEvents {
    NSString *filePath = [self defaultCachePath];
    NSData *data = [NSData dataWithContentsOfFile:filePath];
    if (!data) return @[];

    NSError *error = nil;
    NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
    if (error || ![array isKindOfClass:[NSArray class]]) {
        NSLog(@"[BMSOpMergeCacheManager] 加载缓存失败：%@", error.localizedDescription);
        return @[];
    }

    // 过滤非法结构（确保是 NSDictionary 数组）
    NSMutableArray<NSDictionary *> *validEvents = [NSMutableArray array];
    for (id item in array) {
        if ([item isKindOfClass:[NSDictionary class]]) {
            [validEvents addObject:item];
        }
    }

    return validEvents;
}

- (NSString *)defaultCachePath {
    NSString *dir = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
    return [dir stringByAppendingPathComponent:@"bms_event_cache.json"];
}

- (void)saveEvents:(NSArray<NSDictionary *> *)events {
    if (!events || events.count == 0) return;
    dispatch_async(self.ioQueue, ^{
        NSError *error = nil;
        NSData *data = [NSJSONSerialization dataWithJSONObject:events options:0 error:&error];
        if (error || !data) {
            NSLog(@"[BMSCache] JSON encode failed: %@", error);
            return;
        }
        BOOL success = [data writeToFile:self.cacheFilePath atomically:YES];
        if (!success) {
            NSLog(@"[BMSCache] Write file failed");
        } else {
            NSLog(@"[BMSCache] Events cached (%lu)", (unsigned long)events.count);
        }
    });
}

- (void)loadCachedEventsWithCompletion:(void (^)(NSArray<NSDictionary *> *))completion {
    dispatch_async(self.ioQueue, ^{
        NSData *data = [NSData dataWithContentsOfFile:self.cacheFilePath];
        if (!data) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (completion) completion(@[]);
            });
            return;
        }
        NSError *error = nil;
        NSArray *events = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
        if (!events || ![events isKindOfClass:[NSArray class]]) {
            NSLog(@"[BMSCache] JSON decode failed: %@", error);
            dispatch_async(dispatch_get_main_queue(), ^{
                if (completion) completion(@[]);
            });
            return;
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            if (completion) completion(events);
        });
    });
}

- (void)clearCache {
    dispatch_async(self.ioQueue, ^{
        NSError *error;
        [[NSFileManager defaultManager] removeItemAtPath:self.cacheFilePath error:&error];
        if (error) {
            NSLog(@"[BMSCache] Clear failed: %@", error);
        } else {
            NSLog(@"[BMSCache] Cache cleared");
        }
    });
}

@end

